package com.mmc.aspect;

import com.alibaba.fastjson.JSON;
import com.mmc.anno.RequiresPermissions;
import com.mmc.entity.LoginUser;
import com.mmc.exception.NotPermissionException;
import com.mmc.utils.JwtUtils;
import com.mmc.utils.Logical;
import io.jsonwebtoken.Claims;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
 * 作者：李嘉浩
 * 时间：2024-09-17-14:46
 * 功能：
 */
@Aspect
@Component
public class ProAuthAspect {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Around("@annotation(permissions)")
    public Object innerAround(ProceedingJoinPoint point, RequiresPermissions permissions) throws Throwable {
        String[] permission = permissions.value();
        Logical logical = permissions.logical();
        List<String> permissionList=getPermissionByToken();
        //判断是否拥有权限
        isExistPermission(permission,permissionList,logical);

        return point.proceed();
    }

    private List<String> getPermissionByToken() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String authorization = request.getHeader("Authorization");
        String token = authorization.replace("Bearer ", "");
        Claims claims = JwtUtils.parseToken(token);
        String uuid=claims.get("uuid")+"";
        LoginUser loginUser= JSON.parseObject(stringRedisTemplate.opsForValue().get("access_token"+uuid),LoginUser.class);
        List<String> permissions = loginUser.getPermissions();


        return permissions;
    }

    /**
     * 判断是否有权限访问
     * @param myMethodPermissions
     * @param permissionList
     * @param logical
     */
    private void isExistPermission(String[] myMethodPermissions, List<String> permissionList,Logical logical) {
        boolean flag=true;
        for(String permission:myMethodPermissions){
            if (logical==Logical.AND){
                if (!permissionList.contains(permission)){
                    throw new NotPermissionException("权限不足");
                }
                flag=false;
            }
            if (logical==Logical.OR){
                if (permissionList.contains(permission)){
                    flag=false;
                }
            }
            if (flag){
                throw new NotPermissionException("权限不足");
            }
        }
    }
}
